<template>
  <div class="emp-report-container" v-loading="loading" element-loading-text="加载中...">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon total">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ statsData.totalEmps || 0 }}</div>
            <div class="stat-label">员工总数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon active">
            <i class="el-icon-check"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ teacherCount }}</div>
            <div class="stat-label">班主任</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon inactive">
            <i class="el-icon-close"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ lecturerCount }}</div>
            <div class="stat-label">讲师</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon classes">
            <i class="el-icon-school"></i>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ managerCount }}</div>
            <div class="stat-label">学工主管</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 职位分布饼图 -->
      <el-col :span="12">
        <div class="chart-card" v-loading="chartsLoading">
          <div class="chart-header">
            <h3>职位分布</h3>
            <el-button
              type="text"
              size="mini"
              @click="initJobChart"
              title="刷新图表"
            >
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="chart-content">
            <div ref="jobChart" class="chart"></div>
          </div>
        </div>
      </el-col>

      <!-- 性别分布饼图 -->
      <el-col :span="12">
        <div class="chart-card" v-loading="chartsLoading">
          <div class="chart-header">
            <h3>性别分布</h3>
            <el-button
              type="text"
              size="mini"
              @click="initGenderChart"
              title="刷新图表"
            >
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="chart-content">
            <div ref="genderChart" class="chart"></div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 入职年份趋势 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <div class="chart-card" v-loading="chartsLoading">
          <div class="chart-header">
            <h3>入职年份趋势</h3>
            <el-button
              type="text"
              size="mini"
              @click="initYearChart"
              title="刷新图表"
            >
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="chart-content">
            <div ref="yearChart" class="chart"></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getEmpStats } from '@/api/emp'
import * as echarts from 'echarts'

export default {
  name: 'EmpReport',
  data() {
    return {
      statsData: {
        totalEmps: 0,
        jobCounts: {},
        genderCounts: {},
        yearCounts: {}
      },
      jobChart: null,
      genderChart: null,
      yearChart: null,
      loading: false,
      chartsLoading: false,
      resizeObserver: null,
      themeObserver: null
    }
  },
  computed: {
    // 缓存计算各职位数量
    teacherCount() {
      return this.statsData.jobCounts && this.statsData.jobCounts[1] || 0
    },
    lecturerCount() {
      return this.statsData.jobCounts && this.statsData.jobCounts[2] || 0
    },
    managerCount() {
      return this.statsData.jobCounts && this.statsData.jobCounts[3] || 0
    },
    // 缓存处理职位数据
    processedJobData() {
      if (!this.statsData.jobCounts) return []
      const jobLabels = {
        1: '班主任',
        2: '讲师',
        3: '学工主管',
        4: '教研主管',
        5: '咨询师'
      }
      return Object.entries(this.statsData.jobCounts).map(([key, value]) => ({
        name: jobLabels[key] || `未知职位 ${key}`,
        value
      }))
    },
    // 缓存处理性别数据
    processedGenderData() {
      return [
        { name: '男', value: this.statsData.genderCounts && this.statsData.genderCounts[1] || 0 },
        { name: '女', value: this.statsData.genderCounts && this.statsData.genderCounts[2] || 0 }
      ]
    },
    // 缓存处理年份数据
    processedYearData() {
      if (!this.statsData.yearCounts) return { years: [], counts: [] }
      const years = Object.keys(this.statsData.yearCounts).sort()
      const counts = years.map(year => this.statsData.yearCounts[year])
      return { years, counts }
    },
    // 缓存图表实例数组
    chartInstances() {
      return [this.jobChart, this.genderChart, this.yearChart].filter(Boolean)
    }
  },
  mounted() {
    this.initData()
    this.initResizeObserver()
    this.initThemeObserver()
  },
  beforeDestroy() {
    // 清理图表实例
    this.chartInstances.forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
    this.jobChart = null
    this.genderChart = null
    this.yearChart = null

    // 清理观察器
    if (this.resizeObserver) {
      this.resizeObserver.disconnect()
      this.resizeObserver = null
    }
    if (this.themeObserver) {
      this.themeObserver.disconnect()
      this.themeObserver = null
    }

    // 清理window事件监听器
    if (this._windowResizeHandler) {
      window.removeEventListener('resize', this._windowResizeHandler)
      this._windowResizeHandler = null
    }
  },
  methods: {
    // 防抖工具函数
    debounce(func, wait) {
      let timeout
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout)
          func(...args)
        }
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
      }
    },

    // 优化的数据初始化方法
    async initData() {
      this.loading = true
      this.chartsLoading = true

      try {
        const res = await getEmpStats()
        console.log('Response Data:', res)

        if (res.data.data) {
          this.statsData = {
            totalEmps: res.data.data.totalEmps || 0,
            jobCounts: res.data.data.jobCounts || {},
            genderCounts: res.data.data.genderCounts || {},
            yearCounts: res.data.data.yearCounts || {}
          }
        } else {
          this.statsData = {
            totalEmps: 0,
            jobCounts: {},
            genderCounts: {},
            yearCounts: {}
          }
        }

        // 延迟初始化图表以确保DOM已更新
        this.$nextTick(() => {
          this.initCharts()
          this.chartsLoading = false
        })
      } catch (error) {
        console.error('Error Details:', error)
        this.$message.error('获取数据失败')
        this.chartsLoading = false
      } finally {
        this.loading = false
      }
    },
    // 初始化所有图表
    initCharts() {
      this.initJobChart()
      this.initGenderChart()
      this.initYearChart()
    },

    // 初始化职位分布图表
    initJobChart() {
      if (this.processedJobData.length === 0) {
        console.log('职位统计数据为空')
        return
      }

      if (this.jobChart) {
        this.jobChart.dispose()
      }

      this.jobChart = echarts.init(this.$refs.jobChart)
      this.updateJobChart()
    },

    // 初始化性别分布图表
    initGenderChart() {
      if (this.processedGenderData.every(item => item.value === 0)) {
        console.log('性别统计数据为空')
        return
      }

      if (this.genderChart) {
        this.genderChart.dispose()
      }

      this.genderChart = echarts.init(this.$refs.genderChart)
      this.updateGenderChart()
    },

    // 初始化年份趋势图表
    initYearChart() {
      const { years } = this.processedYearData
      if (years.length === 0) {
        console.log('年份统计数据为空')
        return
      }

      if (this.yearChart) {
        this.yearChart.dispose()
      }

      this.yearChart = echarts.init(this.$refs.yearChart)
      this.updateYearChart()
    },
    // 优化的职位图表更新
    updateJobChart() {
      if (!this.jobChart || this.processedJobData.length === 0) return

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}人 ({d}%)'
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: this.processedJobData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {c}人',
              color: '#606266',
              fontSize: 12
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 15,
              lineStyle: {
                color: '#cccccc'
              }
            }
          }
        ]
      }
      this.jobChart.setOption(option)
    },
    // 优化的性别图表更新
    updateGenderChart() {
      if (!this.genderChart || this.processedGenderData.every(item => item.value === 0)) return

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}人 ({d}%)'
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '70%'],
            data: this.processedGenderData,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {c}人',
              color: '#606266',
              fontSize: 12
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 15,
              lineStyle: {
                color: '#cccccc'
              }
            }
          }
        ]
      }
      this.genderChart.setOption(option)
    },
    // 优化的年份趋势图表更新
    updateYearChart() {
      if (!this.yearChart) return

      const { years, counts } = this.processedYearData
      if (years.length === 0) return

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}年: {c}人'
        },
        xAxis: {
          type: 'category',
          data: years,
          axisLabel: {
            color: '#606266',
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#606266',
            fontSize: 12
          }
        },
        series: [
          {
            type: 'bar',
            data: counts,
            itemStyle: {
              color: '#409EFF'
            },
            barWidth: '60%'
          }
        ]
      }
      this.yearChart.setOption(option)
    },
    // 优化的resize处理
    handleResize() {
      this.chartInstances.forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },

    // 初始化resize观察器
    initResizeObserver() {
      if (window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver(this.debounce(this.handleResize, 100))
        this.resizeObserver.observe(this.$el)
      } else {
        // 降级到window resize事件
        this._windowResizeHandler = this.debounce(this.handleResize, 100)
        window.addEventListener('resize', this._windowResizeHandler)
      }
    },

    // 初始化主题观察器
    initThemeObserver() {
      if (window.MutationObserver) {
        this.themeObserver = new MutationObserver(this.debounce(() => {
          // 主题变化时重新初始化图表
          this.$nextTick(() => {
            this.initCharts()
          })
        }, 200))

        this.themeObserver.observe(document.documentElement, {
          attributes: true,
          attributeFilter: ['class', 'data-theme']
        })
      }
    },

    // 刷新数据
    async refreshData() {
      await this.initData()
    }
  }
}
</script>

<style scoped>
.emp-report-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  color: #333;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  border: 1px solid #e9ecef;
  min-height: 100px;
  height: 100px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 15px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #ff6b9d 0%, #c44569 100%);
}

.stat-icon.inactive {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
}

.stat-icon.classes {
  background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #2d3748;
}

.stat-label {
  font-size: 14px;
  color: #718096;
  margin-bottom: 2px;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 8px;
  padding: 20px;
  height: 400px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid #e9ecef;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.chart-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.chart-header .el-button {
  color: #909399;
  transition: color 0.3s;
}

.chart-header .el-button:hover {
  color: #409EFF;
}

.chart-content {
  height: calc(100% - 60px);
}

.chart {
  width: 100%;
  height: 100%;
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .emp-report-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
}
body.dark-theme .stat-card,
body.dark-theme .chart-card {
  background: linear-gradient(135deg, #232323 0%, #232323 100%) !important;
  border: 1px solid #444 !important;
  color: #fff !important;
  box-shadow: 0 4px 6px rgba(0,0,0,0.3) !important;
}
body.dark-theme .stat-number {
  color: #fff !important;
}
body.dark-theme .stat-label {
  color: #bbb !important;
}
body.dark-theme .chart-header {
  border-bottom: 1px solid #444 !important;
  color: #fff !important;
}
body.dark-theme .el-row {
  color: #fff !important;
}
body.dark-theme .el-col {
  color: #fff !important;
}
body.dark-theme .chart {
  background: transparent !important;
}
</style>

